package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.dto.ScanReturnDTO;
import com.powerbank.user.service.RentalService;
import com.powerbank.user.service.DeviceCommunicationService;
import com.powerbank.user.vo.RentalOrderVO;
import com.powerbank.user.vo.BillingInfoVO;
import com.powerbank.user.vo.DeviceStatusVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

/**
 * 归还流程控制器
 */
@Slf4j
@RestController
@RequestMapping("/return")
public class ReturnController {

    @Autowired
    private RentalService rentalService;

    @Autowired
    private DeviceCommunicationService deviceCommunicationService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 扫码归还充电宝
     */
    @PostMapping("/scan")
    public Result<RentalOrderVO> scanReturn(@RequestBody @Valid ScanReturnDTO returnDTO,
                                            HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        log.info("用户{}开始扫码归还，二维码：{}", userId, returnDTO.getQrCode());
        
        try {
            RentalOrderVO orderVO = rentalService.scanReturn(userId, returnDTO);
            return Result.success("充电宝归还成功，请查看费用明细", orderVO);
        } catch (Exception e) {
            log.error("扫码归还失败：{}", e.getMessage(), e);
            return Result.error("归还失败：" + e.getMessage());
        }
    }

    /**
     * 获取归还费用预览
     */
    @GetMapping("/billing-preview/{orderId}")
    public Result<BillingInfoVO> getReturnBillingPreview(@PathVariable Long orderId,
                                                         HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            BillingInfoVO billingInfo = rentalService.getReturnBillingPreview(userId, orderId);
            return Result.success("费用预览获取成功", billingInfo);
        } catch (Exception e) {
            log.error("获取费用预览失败：{}", e.getMessage(), e);
            return Result.error("获取费用预览失败：" + e.getMessage());
        }
    }

    /**
     * 确认归还和费用结算
     */
    @PostMapping("/confirm/{orderId}")
    public Result<RentalOrderVO> confirmReturn(@PathVariable Long orderId,
                                               HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        log.info("用户{}确认归还订单{}", userId, orderId);
        
        try {
            RentalOrderVO orderVO = rentalService.confirmReturn(userId, orderId);
            return Result.success("归还完成，费用已结算", orderVO);
        } catch (Exception e) {
            log.error("确认归还失败：{}", e.getMessage(), e);
            return Result.error("确认归还失败：" + e.getMessage());
        }
    }

    /**
     * 查询设备状态（归还前检查）
     */
    @GetMapping("/device-status/{deviceCode}")
    public Result<DeviceStatusVO> getDeviceStatus(@PathVariable @NotBlank(message = "设备编码不能为空") String deviceCode) {
        try {
            DeviceStatusVO deviceStatus = deviceCommunicationService.queryDeviceStatus(deviceCode);
            return Result.success("设备状态查询成功", deviceStatus);
        } catch (Exception e) {
            log.error("查询设备状态失败：{}", e.getMessage(), e);
            return Result.error("查询设备状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户当前正在进行的租借订单（用于归还流程）
     */
    @GetMapping("/current-order")
    public Result<RentalOrderVO> getCurrentRentalOrder(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            RentalOrderVO orderVO = rentalService.getCurrentRentalOrder(userId);
            if (orderVO == null) {
                return Result.error("暂无正在进行的租借订单");
            }
            return Result.success("当前订单获取成功", orderVO);
        } catch (Exception e) {
            log.error("获取当前订单失败：{}", e.getMessage(), e);
            return Result.error("获取当前订单失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }
}